﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.WebHost;
using System.Web.Routing;
using System.Web.SessionState;

namespace WebMobie
{
	public static class WebApiConfig
	{
		public static void Register(HttpConfiguration config)
		{
			// Only 1 get function in api controller
			/*
			config.Routes.MapHttpRoute(
			    name: "DefaultApi",
			    routeTemplate: "api/{controller}/{id}",
			    defaults: new { id = RouteParameter.Optional }
			);
			*/
			//support multi get function
			/* 
			var route = config.Routes.MapHttpRoute(
				   name: "ActionApi",
				   routeTemplate: "api/{controller}/{action}/{id}",
				   defaults: new { id = RouteParameter.Optional }
				);
			 */
			//Suport session
			var route = RouteTable.Routes.MapHttpRoute(
			   name: "ActionApi",
			   routeTemplate: "api/{controller}/{action}/{id}",
			   defaults: new { id = RouteParameter.Optional }
			);
			route.RouteHandler = new MyHttpControllerRouteHandler();
			route.RouteHandler = new MyHttpControllerRouteHandler();

			// New code:
			var json = config.Formatters.JsonFormatter;
			json.SerializerSettings.PreserveReferencesHandling =
			    Newtonsoft.Json.PreserveReferencesHandling.Objects;

			config.Formatters.Remove(config.Formatters.XmlFormatter);
		}
	}

	public class MyHttpControllerHandler : HttpControllerHandler, IRequiresSessionState
	{
		public MyHttpControllerHandler(RouteData routeData)
			: base(routeData)
		{
		}
	}
	public class MyHttpControllerRouteHandler : HttpControllerRouteHandler
	{
		protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
		{
			return new MyHttpControllerHandler(requestContext.RouteData);
		}
	}

}
